﻿using System;
using System.Data.Linq;
using System.Linq;
using BKO.Domain.Repositories;

namespace BKO.DataAccesss.Repositories
{
	public class BaseRepository<IEntity, TEntity> : IRepository<IEntity> where TEntity : class, IEntity, new()
	{
		protected readonly DataContext Context;

		public BaseRepository(DataContext context)
		{
			Context = context;
		}

		public IEntity Get()
		{
			return Context.GetTable<TEntity>().FirstOrDefault<IEntity>();
		}

		public IQueryable<IEntity> GetAll()
		{
			return Context.GetTable<TEntity>().AsQueryable<IEntity>();
		}

		public IEntity CreateEmpty()
		{
			return new TEntity();
		}

		public void Add(IEntity entity)
		{
			Context.GetTable<TEntity>().InsertOnSubmit((TEntity)entity);
			Context.SubmitChanges();
		}

		public void Update()
		{
			Context.SubmitChanges();
		}

		public void Delete(IEntity entity)
		{
			Context.GetTable<TEntity>().DeleteOnSubmit((TEntity)entity);
			Context.SubmitChanges();
		}

		public void Clear()
		{
			throw new NotImplementedException();
			//Context.GetTable<TEntity>().DeleteAllOnSubmit();
		}
	}
}
